<template>
  <el-dialog
    title="用户注册"
    :visible.sync="dialogFormVisible"
    center
    class="my-dialog"
    width="603px"
    top="10vh"
    @closed="closedHandler"
  >
    <el-form :model="form" ref="regForm" :rules="rules">
      <el-form-item label="头像" :label-width="formLabelWidth" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="upLoadUrl"
          name="image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" :label-width="formLabelWidth" prop="username">
        <el-input v-model="form.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
        <el-input v-model="form.email" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="手机" :label-width="formLabelWidth" prop="phone">
        <el-input v-model="form.phone" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
        <el-input
          v-model="form.password"
          autocomplete="off"
          show-password
        ></el-input>
      </el-form-item>
      <!-- 图形码 -->
      <el-row>
        <el-col :span="16">
          <el-form-item
            label="图形码"
            :label-width="formLabelWidth"
            prop="code"
          >
            <el-input v-model="form.code" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col :offset="1" :span="7">
          <img class="code-img" :src="codeUrl" alt="" @click="changeCodeUrl" />
        </el-col>
      </el-row>
      <!-- 获取验证码 -->
      <el-row>
        <el-col :span="16">
          <el-form-item
            label="验证码"
            :label-width="formLabelWidth"
            prop="rcode"
          >
            <el-input v-model="form.rcode" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col :offset="1" :span="7">
          <el-button :disabled="this.countDown !== 0" @click="getCode">{{
            btnText
          }}</el-button>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitFrom">
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getSMScode, register } from '../../api/register.js'

export default {
  name: 'register',
  data () {
    return {
      dialogFormVisible: false,
      form: {
        username: '',
        email: '',
        phone: '',
        password: '',
        code: '',
        avatar: '',
        rcode: ''
      },
      formLabelWidth: '72px',
      imageUrl: '',
      upLoadUrl: process.env.VUE_APP_BaseURL + '/uploads',
      codeUrl: process.env.VUE_APP_BaseURL + '/captcha?type=sendsms',
      btnText: '获取用户验证码',
      countDown: 0,
      // 校验规则
      rules: {
        username: [
          {
            required: true,
            message: '用户名不能为空',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 11,
            message: '用户名长度为 2 到 11',
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: '手机号不能为空',
            trigger: 'blur'
          },
          {
            pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: '手机号格式有误',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '邮箱不能为空',
            trigger: 'blur'
          },
          {
            type: 'email',
            message: '邮箱格式有误',
            trigger: 'blur'
          }
        ],
        avatar: [
          {
            required: true,
            message: '头像不能为空',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '密码不能为空',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 18,
            message: '密码的长度为 6 到 18',
            trigger: 'blur'
          }
        ],
        code: [
          {
            required: true,
            message: '图形验证码不能为空',
            trigger: 'blur'
          },
          {
            min: 4,
            max: 4,
            message: '图形验证码的长度为 4',
            trigger: 'blur'
          }
        ],
        rcode: [
          {
            required: true,
            message: '短信验证码不能为空',
            trigger: 'blur'
          },
          {
            min: 4,
            max: 4,
            message: '短信验证码的长度为 4',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    closedHandler () {
      // 清空表单
      this.$refs.regForm.resetFields()
      this.imageUrl = ''
    },
    // 提交按钮
    submitFrom () {
      this.$refs.regForm.validate(valid => {
        if (valid) {
          const { username, email, phone, password, avatar, rcode } = this.form
          register({ username, email, phone, password, avatar, rcode }).then(
            res => {
              console.log(res)
              if (res.data.code === 200) {
                this.$message.success('注册成功')
                this.dialogFormVisible = false
              } else {
                this.$message.error(res.data.message)
              }
            }
          )
        } else {
          this.$message.error('数据格式有误,请检查')
          return false
        }
      })
    },

    getCode () {
      this.$refs.regForm.validateField(['phone', 'code'], errorMessage => {
        console.log(errorMessage)
      })
      // 获取验证码
      const { phone, code } = this.form
      if (phone === '' || code === '') {
        this.$message.error('请输入手机和图形验证码')
        return
      }
      // 计时器开始
      if (this.countDown === 0) {
        // 点击时如果为0 则开始定时器
        this.countDown = 5
        // 点击后直接修改文本 这样才能显示最开始的5
        this.btnText = `请等待 ( ${this.countDown} ) 秒`
        // 开启定时器
        const timeID = setInterval(() => {
          // 每秒自减
          this.countDown--
          // 当达成条件
          if (this.countDown === 0) {
            this.btnText = '获取用户验证码'
            clearInterval(timeID)
            // 到达0秒 就打断函数
            return
          }
          this.btnText = `请等待 ( ${this.countDown} ) 秒`
        }, 1000)
      }

      getSMScode({ phone, code }).then(res => {
        console.log(res)
        if (res.data.code === 0) {
          this.$message.error(res.data.message)
        } else {
          this.$message.success('验证码:' + res.data.data.captcha)
        }
      })
    },
    changeCodeUrl () {
      // 点击后添加随机数或者时间戳
      // 随机数
      // this.codeUrl =
      //   process.env.VUE_APP_BaseURL + '/captcha?type=sendsms&t=' + Math.random()
      // 时间戳
      this.codeUrl =
        process.env.VUE_APP_BaseURL + '/captcha?type=sendsms&t=' + Date.now()
      // console.log(this.codeUrl)
    },
    handleAvatarSuccess (res, file) {
      // console.log(res)
      this.imageUrl = URL.createObjectURL(file.raw)

      this.$refs.regForm.clearValidate('avatar')

      this.form.avatar = res.data.file_path
      console.log(this.form.avatar)
    },
    beforeAvatarUpload (file) {
      const isJPG =
        ['image/jpeg', 'image/png', 'image/gif'].indexOf('image/jpeg') !== -1
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="less">
.my-dialog {
  .el-dialog__header {
    padding: 18px 20px;
    background: linear-gradient(to right, #01c6fa 28%, #1493fa 96%);
  }
  .el-dialog__title {
    color: white;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .avatar-uploader {
    text-align: center;
  }
  .code-img {
    display: block;
    width: 100%;
  }
  .el-dialog--center .el-dialog__body {
    padding-left: 15px;
  }
}
</style>
